﻿using System;
using System.IO;
using Newtonsoft.Json;
using System.Net.DnsToolkit.Packet;
using System.Net.DnsToolkit.Serializer;

namespace System.Net.DnsToolkit.Serializer.Json {
    public class MessageWriter : IMessageWriter<TextWriter> {

        private readonly JsonConverter[] _jsonConverters;

        public MessageWriter(params JsonConverter[] jsonConverters) {
            _jsonConverters = jsonConverters;
        }

        public void Write(TextWriter destination, IMessage message) {
            InternalWrite(destination, message, Formatting.None);
        }

        public void Write(TextWriter destination, IMessage message, bool useCompression) {
            InternalWrite(destination, message,
                useCompression ? Formatting.None : Formatting.Indented);
        }

        private void InternalWrite(TextWriter destination, IMessage message, Formatting formatting) {

            string json = JsonConvert.SerializeObject(
                message,
                formatting,
                _jsonConverters
                );

            destination.WriteLine(json);
        }



    }
}

